import React from 'react'
import { Layout, Menu, Dropdown, Avatar } from 'antd'
import { connect } from 'react-redux'

import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { withRouter } from 'react-router'

const { Header } = Layout
function TopHeader(props) {
  const {
    role: { roleName },
    username,
  } = JSON.parse(localStorage.getItem('token'))

  const changeCollapsed = () => {
    props.changeCollapsed()
  }

  const menu = (
    <Menu>
      <Menu.Item key={1}>{roleName}</Menu.Item>
      <Menu.Item
        key={2}
        danger
        onClick={() => {
          localStorage.removeItem('token')
          props.history.replace('/login')
        }}
      >
        退出
      </Menu.Item>
    </Menu>
  )
  return (
    <Header className="site-layout-background" style={{ padding: '0 16px' }}>
      {props.isCollapsed ? (
        <MenuUnfoldOutlined onClick={changeCollapsed}></MenuUnfoldOutlined>
      ) : (
        <MenuFoldOutlined onClick={changeCollapsed}></MenuFoldOutlined>
      )}

      <div style={{ float: 'right' }}>
        <span>
          欢迎<span style={{ color: '#1890ff' }}>{username}</span>回来
        </span>
        <Dropdown overlay={menu}>
          <Avatar size="large" icon={<UserOutlined />} />
        </Dropdown>
      </div>
    </Header>
  )
}
const mapStateToProps = (state) => {
  // console.log(state)
  return {
    ...state.collapsedReducer,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    changeCollapsed() {
      dispatch({
        type: 'change-collapsed',
      })
    },
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(TopHeader))

